package com.cheer.security;

import com.cheer.entity.User;
import com.cheer.enums.CaptchaEnum;
import com.cheer.vo.Result;
import com.cheer.vo.UserVO;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author cheer
 */
@Component
public class RestAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private UserInfoHolder userInfoHolder;

    @Override
    public void onAuthenticationSuccess(
            HttpServletRequest request, HttpServletResponse response, Authentication authentication)
            throws IOException {

        User user = userInfoHolder.getUser();
        UserVO adminVO = new UserVO();
        adminVO.setUsername(user.getUsername());
        adminVO.setName(user.getName());
        adminVO.setRole(user.getRole());

        // 删除登录验证码产生的 Session
        HttpSession session = request.getSession();
        session.removeAttribute(CaptchaEnum.LOGIN.getAttribute());
        session.removeAttribute(SecurityConfig.FAILED_LOGIN);

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        response.getWriter().println(objectMapper.writeValueAsString(Result.success(adminVO)));
        response.getWriter().flush();


    }
}
